<?php

namespace App\Http\Controllers\Api\Admin;

use App\AuthorizerInfo;
use App\AvailableUrl;
use App\Enterprise;
use App\Http\Controllers\Api\WeChatThirdController;
use App\Http\Services\AdminManager;
use App\Http\Services\ToolsManager;
use App\PlatformConfig;
use App\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;

class PlatformController extends Controller
{

    public function bindDomain(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterprise_id  =$request->input('enterprise_id') ?? 0;
        $domain         =$request->input('domain') ?? '';

        $remark         =$request->input('remark') ?? '';
        $expire_date    =$request->input('expire_date') ?? '';

        $id             =$request->input('id') ?? 0;
        if (!$enterprise_id)
            return response()->json(['level'=>'error','message'=>'企业id错误']);
        $domain=strtolower($domain);
        $array=[
            'http://',
            'https://',
        ];
        $domain     = trim(str_replace($array,'',$domain));
        if (!$domain)
            return response()->json(['level'=>'error','message'=>'域名错误']);

//        $data=AvailableUrl::whereDomain($domain)->first();
//        if ($data)
//            return response()->json(['level'=>'error','message'=>'该域名已经添加过了']);

        $info=AuthorizerInfo::whereEnterpriseId($enterprise_id)
            ->whereIn('status',[1,3,4,5,6])
            ->first();
        if (!$info)
            return response()->json(['level'=>'error','message'=>'该小程序目前不可设置']);
        try {
            //TODO 调用添加DNS解析记录接口
        } catch (Exception $exception){
            Log::error('DNS API ERROR:'.$exception->getMessage());
            return response()->json(['level'=>'error','message'=>'域名解析错误']);
        }
        $data=AvailableUrl::whereEnterpriseId($enterprise_id)->first();
        if (!$data){
            $data=new AvailableUrl();
            $data->enterprise_id    = $enterprise_id;
            $data->miniprogram_appid= $info->authorizer_appid;
        }

        $data->domain       = $domain;
        if ($expire_date)
            $data->expire_date  = $expire_date;
        $data->remark       = $remark ?? '';
        $data->save();
        return response()->json(['level'=>'success','message'=>'success','data'=>$data]);
    }

    public function getBindConfig(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterprise_id=$request->input('enterprise_id');
        $data=AvailableUrl::whereEnterpriseId($enterprise_id)->first();
        return response()->json(['level'=>'success','message'=>'success','data'=>$data]);
    }

    public function setPlatformConfig(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $component_appid    =$request->input('component_appid') ?? '';
        $component_secret   =$request->input('component_secret')?? '';
        $token              =$request->input('token')           ?? '';
        $aes_key            =$request->input('aes_key')         ?? '';
        $remark             =$request->input('remark')          ?? '';

        $component_appid    =trim($component_appid);
        $component_secret   =trim($component_secret);
        $token              =trim($token);
        $aes_key            =trim($aes_key);
        if (!$component_appid)
            return response()->json(['level'=>'error','message'=>'请输入平台APPID']);
        if (!$component_secret)
            return response()->json(['level'=>'error','message'=>'请输入平台APPID']);
        if (!$token)
            return response()->json(['level'=>'error','message'=>'请输入消息校验Token']);

        if (strlen($aes_key) !=43)
            return response()->json(['level'=>'error','message'=>'消息加解密Key长度错误，正常长度应为43位']);

        $config =PlatformConfig::whereComponentAppid($component_appid)->first();
        if (!$config){
            $config = new PlatformConfig();
            $config->component_appid = $component_appid;
        }
        $config->component_secret   =$component_secret;
        $config->token              =$token;
        $config->aes_key            =$aes_key;
        $config->remark             =$remark;
        $config->save();
        return response()->json(['level'=>'success','message'=>'设置成功']);

    }
    public function getPlatformConfig(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $config =PlatformConfig::first();
        if (!$config){
            $config = new PlatformConfig();
            $config->component_appid = '';
            $config->save();
        }
        $config->component_appid    = ToolsManager::coverString($config->component_appid);
        $config->component_secret   = ToolsManager::coverString($config->component_secret);
        $config->aes_key            = ToolsManager::coverString($config->aes_key);
        $config->token              = ToolsManager::coverString($config->token);
        return response()->json(['level'=>'success','message'=>'success','data'=>$config]);

    }
    /**
     * 获取授权小程序列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthorizerList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       =$request->input('page')  ?? 1;
        $limit      =$request->input('limit') ?? 5;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit,
            'total'=>0
        ];
        $page=$page-1;


        $data=AuthorizerInfo::orderByDesc('id');
        $page_info['total']=$data->count();
        $data=$data->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            /** @var AuthorizerInfo $item */
            foreach ($data as $item){
                $item->status_name  = AuthorizerInfo::getStatusName($item->status);
                $item->enterprise_info = Enterprise::whereId($item->enterprise_id)->first();
                $item->miniprogran_info=self::getMiniProgramInfo($item->authorizer_appid);
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$page_info]);
    }

    /**
     * 获取授权小程序的基本信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMiniProgramAccountBasicInfo(Request $request)
    {
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '该小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        //easyWechat默认返回的是数组
        $data=self::getMiniProgramInfo($thisProgramRecord->authorizer_appid);
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
    }

    /**
     * 设置小程序服务器域名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDomain(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $action             = $request->input('action')   ?? 'get';
        $requestDomain      = $request->input('request_domain') ?? [];
        $wsRequestDomain    = $request->input('ws_request_domain') ?? [];
        $uploadDomain       = $request->input('upload_domain') ?? [];
        $downloadDomain      = $request->input('download_domain') ?? [];
        if (!in_array($action,['add','delete','set','get']))
            return response()->json(['level'=>'error','message'=>'请输入正确的操作类型','data'=>[]]);
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        $payload=[
            'action'=>$action,
        ];
        if ($action!='get'){
            $payload['requestdomain']   =is_array($requestDomain)   ? $requestDomain    : [];
            $payload['wsrequestdomain'] =is_array($wsRequestDomain) ? $wsRequestDomain  : [];
            $payload['uploaddomain']   =is_array($uploadDomain)     ? $uploadDomain     : [];
            $payload['downloaddomain']   =is_array($downloadDomain) ? $downloadDomain   : [];
        }

        try {
            $data=$thisProgram->domain->modify($payload);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        } catch (Exception $e){
            return response()->json(['level' => 'error', 'message' => 'Exception!!!'.$e->getMessage()]);
        } catch (HttpException $e){
            return response()->json(['level' => 'error', 'message' => 'HttpException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 设置小程序业务域名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setWebViewDomain(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $action             = $request->input('action')   ?? 'get';
        $webViewDomain      = $request->input('web_view_domain') ?? [];
        if (!in_array($action,['add','delete','set','get']))
            return response()->json(['level'=>'error','message'=>'请输入正确的操作类型','data'=>[]]);
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        $domain=[];
        if ($action!='get'){
            $domain  = is_array($webViewDomain)   ? $webViewDomain    : [];
        }

        try {
            $data=$thisProgram->domain->setWebviewDomain($domain,$action);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 设置小程序名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setNickname(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $name               = $request->input('nickname')   ?? '';
        $id_card            = $request->input('id_card')   ?? '';
        $license            = $request->input('license')   ?? '';
        $other_stuff        = $request->input('naming_other_stuff')   ?? [];

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->setting->setNickname($name, $id_card, $license, $other_stuff);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);

    }

    /**
     * 检查名称是否可用
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkVerifyNickname(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name               = $request->input('nickname')   ?? '';
        $mini_program_appid = $request->input('mp_appid') ?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->setting->isAvailableNickname($name);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0){
            if ($data['hit_condition'])
                return response()->json(['level'=>'success','message'=>'命中关键词，'.$data['wording'],'data'=>$data]);
            else
                return response()->json(['level'=>'success','message'=>'名称可用','data'=>$data]);
        } else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);

    }

    /**
     * 查询改名审核状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNicknameSettingStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $audit_id           = $request->input('audit_id')   ?? '';

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->setting->getNicknameAuditStatus($audit_id);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);

    }

    /**
     * 修改头像
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setHeadImage(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $media_id           = $request->input('media_id')   ?? '';

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->account->updateAvatar($media_id);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }


    //成员管理

    /**
     * 绑定微信用户为体验者
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindExperiencer(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $wechat_id          = $request->input('wechat_id') ?? '';

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->tester->bind($wechat_id);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 解除绑定体验者
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbindExperiencer(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        $wechat_id          = $request->input('wechat_id') ?? '';
        $user_str           = $request->input('user_str') ?? '';

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->tester->unbind($wechat_id);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 获取绑定的体验者
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBindExperiencer(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid') ?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->tester->list();
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }
    //代码管理

    /**
     * 获取草稿列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemplateDraftList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $thisPlatform = self::getPlatformInstance();
        try {
            $data = $thisPlatform->code_template->getDrafts();
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 把草稿设为模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addToTemplate(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $draft_id=$request->input('draft_id') ?? '';
        if (!$draft_id)
            return response()->json(['level'=>'error','message'=>'请选择草稿']);

        $thisPlatform = self::getPlatformInstance();
        try {
            $data = $thisPlatform->code_template->createFromDraft($draft_id);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 获取模板列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemplateList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $thisPlatform = self::getPlatformInstance();
        try {
            $data = $thisPlatform->code_template->list();
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 删除模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delTemplate(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $template_id=$request->input('template_id') ?? '';
        if (!is_numeric($template_id))
            return response()->json(['level'=>'error','message'=>'请选择模板']);
        $thisPlatform = self::getPlatformInstance();
        try {
            $data = $thisPlatform->code_template->delete($template_id);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 上传代码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadMiniProgramCode(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid')   ?? '';
        $template_id        = $request->input('template_id')?? '';
        $ext_json           = $request->input('ext_json')?? '';
        $user_version       = $request->input('user_version')?? '1.0.0.default';
        $user_desc          = $request->input('user_desc')?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
//        $ext_json=json_encode([
//            'extAppid'=>$mini_program_appid,
//            'extEnable'=>false
//        ]);
        try {
            $data = $thisProgram->code->commit($template_id,$ext_json,$user_version,$user_desc);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 获取已上传的代码的页面列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUploadPageList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid')   ?? '';

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->code->getPage();
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 获取体验版二维码
     * @param Request $request
     * @return \EasyWeChat\Kernel\Http\Response
     */
    public function getExperienceQRCode(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid')   ?? '';
        $path               = $request->input('path')       ?? '';

        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->code->getQrCode(urlencode($path));
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }

        return $data;
    }

    /**
     * 提交小程序审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function submitCodeToReview(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid')   ?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->code->submitAudit([]);
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0)
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    /**
     * 发布小程序
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function publicMiniProgram(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid')   ?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->code->release();
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0){
            $thisProgramRecord->status=6;
            $thisProgramRecord->save();
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        }

        else
            return response()->json(['level'=>'error','message'=>$data['errmsg'],'data'=>$data]);
    }

    public function getReviewStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $mini_program_appid = $request->input('mp_appid')   ?? '';
        if (!$mini_program_appid)
            return response()->json(['level' => 'error', 'message' => '请输入要小程序appid']);
        $thisProgramRecord = AuthorizerInfo::whereAuthorizerAppid($mini_program_appid)->first();
        if (!$thisProgramRecord)
            return response()->json(['level' => 'error', 'message' => '要查询的小程序appid暂时还未授权给平台']);
        if(!$thisProgramRecord->authorizer_refresh_token)
            return response()->json(['level' => 'error', 'message' => '该小程序授权未完成']);
        $thisProgram = self::getMiniProgramInstance($thisProgramRecord);
        try {
            $data = $thisProgram->code->getLatestAuditStatus();
        } catch (InvalidConfigException $e) {
            return response()->json(['level' => 'error', 'message' => 'InvalidConfigException!!!'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level' => 'error', 'message' => 'GuzzleException!!!'.$e->getMessage()]);
        } catch (Exception $e){
            return response()->json(['level' => 'error', 'message' => 'Exception!!!'.$e->getMessage()]);
        } catch (HttpException $e){
            return response()->json(['level' => 'error', 'message' => 'HttpException!!!'.$e->getMessage()]);
        }
        if ($data['errcode']==0){
            if ($data['status']==0)
                $data['status_name']='审核成功';

            if ($data['status']==1)
                $data['status_name']='审核被拒绝';

            if ($data['status']==2)
                $data['status_name']='审核中';

            if ($data['status']==3)
                $data['status_name']='已撤回';
            return response()->json(['level'=>'success','message'=>'操作成功','data'=>$data]);
        } else{
            $data['status']=-1;
            $data['status_name']='未提交审核';
            return response()->json(['level'=>'success','message'=>$data['errmsg'],'data'=>$data]);
        }

    }


    /**
     * 获取小授权程序实例
     * @param AuthorizerInfo $thisProgramRecord
     * @return \EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Application
     * @author cmj
     */
    private static function getMiniProgramInstance(AuthorizerInfo $thisProgramRecord){
        $config = WeChatThirdController::getPlatformConfig();
        $openPlatform   = Factory::openPlatform($config);
        $miniProgram    = $openPlatform->miniProgram($thisProgramRecord->authorizer_appid, $thisProgramRecord->authorizer_refresh_token);
        return $miniProgram;
    }

    /**
     * 获取平台实例
     * @param null $config
     * @return \EasyWeChat\OpenPlatform\Application
     */
    private static function getPlatformInstance($config=null){
        $config         = $config ?? WeChatThirdController::getPlatformConfig();
        return Factory::openPlatform($config);
    }

    /**
     * @param null $config
     * @return \EasyWeChat\OpenPlatform\Application
     */
    public static function getPublicPlatformInstance($config=null){
        return self::getPlatformInstance($config);
    }

    /**
     * 获取小程序的基本信息
     * @param $appId
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    private static function getMiniProgramInfo($appId){
        $config         = WeChatThirdController::getPlatformConfig();
        $openPlatform   = Factory::openPlatform($config);
        try{
            $data=$openPlatform->getAuthorizer($appId);
        } catch (Exception $exception){
            Log::error('private static function getMiniProgramInfo ERROR:'.$exception->getMessage());
            return [];
        }
        return $data;
    }
}
